<?php

namespace App\Http\Controllers\Configuration\Wechat;

use App\Entities\WechatConfig;
use Illuminate\Http\Request;
use Illuminate\Container\Container;

class WebApiController
{
    public function get(Request $request)
    {
        $groupCode = $request->get('group_code',$request->session()->get('groupcode'));

        $config = WechatConfig::query()->where('group_code', $groupCode)->first();

        if (!$config) {
            return response()->success();
        }

        return response()->success();
    }

    public function getAuthorizationWechat(Request $request)
    {
        $code = $request->get('group_code', $request->session()->get('groupcode'));

        $config = WechatConfig::query()->where('group_code', $code)->first();
        if (empty($config)) {
            $config = [];
        }

        return response()->success($config);
    }

    public function set(Request $request)
    {
        $factory = Container::getInstance()->make('validator');
        $code = $request->session()->get('groupcode');
        if($request->json('type') =='pay'){
            $input = [
                'group_code' => $request->json('group_code', $code),
                'merchant_id'=> $request->json('merchant_id'),
                'key' => $request->json('key'),
                'cert_path' => $request->json('cert_path'),
                'key_path' => $request->json('key_path'),
            ];
            $validator = $factory->make($input, [
                'group_code' => 'required',
                'merchant_id'     => 'required',
                'key' => 'required',
                'cert_path' => 'required',
                'key_path' => 'required',
            ]);
        }else{
            $input = [
                'group_code' => $request->json('group_code', $code),
                'app_id'     => $request->json('app_id'),
                'app_secret' => $request->json('app_secret'),
            ];
            $validator = $factory->make($input, [
                'group_code' => 'required',
                'app_id'     => 'required',
                'app_secret' => 'required',
            ]);
        }

        if ($validator->fails()) {
            return response()->failed($validator->errors()->first());
        }

        $config = WechatConfig::query()->where('group_code', $input['group_code'])->first();

        if (null === $config) {
            $config = new WechatConfig();
        }

        if ($config->fill($input) && $config->save()) {
            return response()->success();
        }

        return response()->failed('配置失败');
    }
}
